package com.archgeek.java.conc.thread;

/**
 * @author pizhihui
 * @date 2023-04-20 18:20
 */
public class ThreadWaitNotifyTest {

    public static void main(String[] args) {


        LaoBao laoBao = new LaoBao();

        QingGuan qingGuan = new QingGuan(laoBao);
        KeGuan keGuan = new KeGuan(laoBao);

        new Thread(qingGuan).start();
        new Thread(keGuan).start();

    }

}

class QingGuan implements Runnable {

    LaoBao baozi;

    public QingGuan(LaoBao baozi) {
        this.baozi = baozi;
    }

    @Override
    public void run() {
        int i = 1;
        while (true) {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            if (i == 1) {
                try {
                    baozi.workQingGuan("苍田野子", "500 日元");
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            } else {
                try {
                    baozi.workQingGuan("花田岗子", "800 日元");
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
            i = (i + 1) % 2;
        }
    }
}

class KeGuan implements Runnable{
    LaoBao baozi;

    public KeGuan(LaoBao baozi) {
        this.baozi = baozi;
    }

    @Override
    public void run() {
        while (true) {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            try {
                baozi.drinkTea();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
    }
}


class LaoBao {
    private String qingGuan = null;
    private String price = null;
    private boolean workState = true;

    public synchronized void workQingGuan(String qingGuan, String price) throws InterruptedException {
        if (!workState) {
            wait();
        }
        this.qingGuan = qingGuan;
        this.price = price;
        workState = false;
        notify();

    }

    public synchronized void drinkTea() throws InterruptedException {
        if (workState) {
            wait();
        }
        System.out.println("聊风月：" + qingGuan);
        System.out.println("茶水费：" + price);
        System.out.println("  " + "  " + "  " + "  " + "  " + "  " + "  " + "  " + "  " + "  " + qingGuan + "完事" + "准备 ... ...");
        System.out.println("****************************************");
        workState = true;
        notify();

    }

}

